import { Cascader } from 'antd-mobile';
import { useEffect, useState } from 'react';
import { excludedOptions } from '../../types';
import regions from '../m_receipt_picker/area.json';
interface Props {
  provinceName?: string;
  cityName?: string;
  countyName?: string;
  excludedList: excludedOptions;
  onChange: (v: string[]) => void;
}
interface Options {
  value?: string;
  label: string;
  disabled?: boolean;
  children?: Options[];
}

export default function AreaPicker({ provinceName, cityName, countyName, excludedList, onChange }: Props) {
  const [visible, setvisible] = useState(false);
  const [regionsList, setregionsList] = useState<Options[]>(regions);
  const [value, setValue] = useState<string[]>([]);

  useEffect(() => {
    const filefilterRegions = filterRegions(regions, excludedList);
    let data: Options[] =
      filefilterRegions && filefilterRegions.length > 0 ? filefilterRegions : [{ label: '暂无可选城市' }];
    setregionsList(data);
  }, [excludedList]);

  // 遍历去除禁选地区
  function filterRegions(regionsList: Options[], excludedRegions: excludedOptions) {
    return regionsList
      .filter((provinceObj) => !excludedRegions.provinces.includes(provinceObj.label))
      .map((provinceObj) => ({
        label: provinceObj.label,
        children: provinceObj
          .children!.filter((cityObj: Options) => !excludedRegions.cities.includes(cityObj.label))
          .map((cityObj: Options) => ({
            label: cityObj.label,
            children: cityObj.children!.filter((dist: Options) => !excludedRegions.district.includes(dist.label)),
          })),
      }));
  }
  function convertValueToLabel(data: Options | Options[]): any {
    if (Array.isArray(data)) {
      // 若为数组，对每个元素递归调用此函数
      return data.map((item) => convertValueToLabel(item));
    } else if (typeof data === 'object' && data !== null) {
      const newObj = { ...data };
      newObj.value = newObj.label;
      if (newObj.children) {
        newObj.children = convertValueToLabel(newObj.children);
      }
      return newObj;
    }
    return data;
  }

  let _value = provinceName + ' ' + cityName + ' ' + countyName;
  let options = convertValueToLabel(regionsList);
  return (
    <div>
      <div onClick={() => setvisible(true)} className={`value omit-text ${!!_value.trim() ? '' : 'place-holder'}`}>
        {!!_value.trim() ? _value : '请选择地区'}
      </div>
      <Cascader
        visible={visible}
        options={options}
        onClose={() => setvisible(false)}
        value={value}
        onConfirm={(v: any) => {
          if (v) {
            onChange(v);
          }
        }}
        onSelect={(val: any, extend) => {
          if (val.length === 3) {
            onChange(val);
            setValue(val);
            setvisible(false);
          }
        }}
      ></Cascader>
    </div>
  );
}
